import java.io.File;
import java.io.FileNotFoundException;
import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * prezrie TeX subor na citacie ktore potrebujeme vybrat z BiBu
 * @author cerko
 *
 */
public class RefAnalyzer {
	
	private File texInput;
	private String content;
	
	public RefAnalyzer (){
		
	}
	
	/**
	 * nacita citacie ktore potrebujeme do setu a vrati, rozdeli na citacie a pridava vysledky getRefsInGroup
	 * @param texInput - TeX input subor v ktorom hladame citacie
	 * @return - set potrebnych referencii
	 * @throws FileNotFoundException
	 */
	public Set<String> getUsedRefs(File texInput) throws FileNotFoundException{
		this.texInput = texInput;
		Set<String> usedRefs = new HashSet<String>();
		loadContent();
		Pattern citationPattern = Pattern.compile("\\\\citep?\\{(.*?)\\}");
		Matcher matcher = citationPattern.matcher(content);
		//System.out.println(content);
		while (matcher.find()) {
			//System.out.print("Start index: " + matcher.start());
			//System.out.print(" End index: " + matcher.end() + " ");
			//System.out.println(matcher.group());
			usedRefs.addAll(getRefsInGroup(matcher.group()));
		}
		//System.out.println(usedRefs.toString());
		return usedRefs;
	}
	
	/**
	 * nahra subor do stringu nech ho mozeme matchovat
	 * @throws FileNotFoundException
	 */
	public void loadContent() throws FileNotFoundException{
		Scanner scanner = new Scanner(texInput);
		content = scanner.useDelimiter("\\A").next();
		scanner.close();
	}
	
	/**
	 * najde vsetky referencie v citate ak ich je viac a vrati ich set
	 * @param _group - cast textu v ktorej hladame
	 * @return - set potrebnych referencii z tejto casti
	 */
	public Set<String> getRefsInGroup(String _group){
		Set<String> refs = new HashSet<String>();
		String group = _group;
		group = group.replaceAll("\\\\citep?\\{", "");
		group = group.replace("}", "");
		group = group.replaceAll(" ", "");
		if (group.isEmpty()){
			return refs;
		}
		Scanner groupScanner = new Scanner(group);
		groupScanner.useDelimiter(",");
		while (groupScanner.hasNext()){
			refs.add(groupScanner.next());
		}
		groupScanner.close();
		return refs;
	}
}
